<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加试题</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/font/bootstrap-icons.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>添加试题</h2>
            <a href="/teacher/question/manage" class="btn btn-secondary">
                <i class="bi bi-arrow-left"></i> 返回列表
            </a>
        </div>
        
        <div class="card">
            <div class="card-body">
                <form id="addQuestionForm">
                    <div class="mb-3">
                        <label for="courseId" class="form-label">所属课程</label>
                        <select class="form-select" id="courseId" name="courseId" required>
                            <option value="">请选择课程</option>
                            <option th:each="course : ${courses}" 
                                    th:value="${course.courseId}" 
                                    th:text="${course.courseName}">课程名称</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="questionType" class="form-label">题目类型</label>
                        <select class="form-select" id="questionType" name="questionType" required>
                            <option value="">请选择题目类型</option>
                            <option value="choice">选择题</option>
                            <option value="fill">填空题</option>
                            <option value="essay">简答题</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="questionContent" class="form-label">题目内容</label>
                        <textarea class="form-control" id="questionContent" name="questionContent" rows="3" required></textarea>
                    </div>
                    
                    <div class="mb-3" id="optionsContainer">
                        <label class="form-label">选项</label>
                        <div id="optionsList">
                            <div class="input-group mb-2">
                                <span class="input-group-text">A</span>
                                <input type="text" class="form-control" name="options">
                            </div>
                            <div class="input-group mb-2">
                                <span class="input-group-text">B</span>
                                <input type="text" class="form-control" name="options">
                            </div>
                            <div class="input-group mb-2">
                                <span class="input-group-text">C</span>
                                <input type="text" class="form-control" name="options">
                            </div>
                            <div class="input-group mb-2">
                                <span class="input-group-text">D</span>
                                <input type="text" class="form-control" name="options">
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="questionAnswer" class="form-label">答案</label>
                        <input type="text" class="form-control" id="questionAnswer" name="questionAnswer" required>
                        <div class="form-text">选择题填写选项字母（如：A），填空题和简答题直接填写答案</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="questionScore" class="form-label">分值</label>
                        <input type="number" class="form-control" id="questionScore" name="questionScore" min="1" max="100" required>
                    </div>
                    
                    <div class="text-center">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-save"></i> 保存
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/axios.min.js"></script>
    <script>
        document.getElementById('questionType').addEventListener('change', function() {
            const optionsContainer = document.getElementById('optionsContainer');
            const questionType = this.value;
            const optionInputs = document.getElementsByName('options');
            
            if (questionType === 'essay' || questionType === 'fill') {
                optionsContainer.style.display = 'none';
                Array.from(optionInputs).forEach(input => {
                    input.removeAttribute('required');
                });
            } else {
                optionsContainer.style.display = 'block';
                Array.from(optionInputs).forEach(input => {
                    input.setAttribute('required', 'required');
                });
            }
        });
        
        document.getElementById('addQuestionForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const questionType = document.getElementById('questionType').value;
            const answerInput = document.getElementById('questionAnswer').value;
            let finalAnswer = answerInput;
            let options = null;
            
            console.log('题目类型:', questionType);
            console.log('原始答案:', answerInput);
            
            // 处理选择题答案和选项
            if (questionType === 'choice') {
                const optionInputs = Array.from(document.getElementsByName('options')).map(input => input.value);
                options = JSON.stringify(optionInputs);
                console.log('选项数据:', options);
                
                if (answerInput.length === 1) { // 单选题
                    const optionIndex = answerInput.toUpperCase().charCodeAt(0) - 65;
                    finalAnswer = optionInputs[optionIndex];
                } else { // 多选题
                    const selectedOptions = answerInput.toUpperCase().split('').map(letter => {
                        const optionIndex = letter.charCodeAt(0) - 65;
                        return optionInputs[optionIndex];
                    });
                    finalAnswer = selectedOptions.join('|');
                }
            } else {
                // 非选择题直接使用输入的答案
                finalAnswer = answerInput.trim();
                options = null;
            }
            
            console.log('处理后的答案:', finalAnswer);
            
            // 验证必填字段
            if (!document.getElementById('courseId').value) {
                alert('请选择所属课程');
                return;
            }
            if (!document.getElementById('questionContent').value.trim()) {
                alert('请输入题目内容');
                return;
            }
            if (!finalAnswer.trim()) {
                alert('请输入答案');
                return;
            }
            if (!document.getElementById('questionScore').value) {
                alert('请输入分值');
                return;
            }
            
            const formData = {
                courseId: document.getElementById('courseId').value,
                type: questionType,
                content: document.getElementById('questionContent').value.trim(),
                options: options,
                answer: finalAnswer,
                score: document.getElementById('questionScore').value
            };
            
            console.log('提交的数据:', formData);
            
            // 显示加载提示
            const submitButton = document.querySelector('button[type="submit"]');
            const originalText = submitButton.innerHTML;
            submitButton.disabled = true;
            submitButton.innerHTML = '<i class="bi bi-hourglass-split"></i> 保存中...';
            
            axios.post('/teacher/question/add', formData)
                .then(response => {
                    console.log('服务器响应:', response.data);
                    if (response.data === 'success') {
                        alert('添加成功');
                        window.location.href = '/teacher/question/manage';
                    } else {
                        alert(response.data);
                    }
                })
                .catch(error => {
                    console.error('提交错误:', error);
                    alert('添加失败：' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    submitButton.disabled = false;
                    submitButton.innerHTML = originalText;
                });
        });
    </script>
</body>
</html> 